package com.xiyou.week05.binarySearch;

/**
 * 875. 爱吃香蕉的珂珂
 *
 * @ClassName：MinEatingSpeed
 * @Author：西柚
 * @Date：2022/1/28 2:47 下午
 * @Versiion：1.0
 */
public class MinEatingSpeed {

    /**
     * 输入: piles = [3,6,7,11], H = 8
     * 输出: 4
     *
     * @param piles
     * @param h
     * @return
     */
    public int minEatingSpeed(int[] piles, int h) {
        int max = 0;
        for (int p : piles) {
            max = Math.max(max, p);
        }
        int left = 1;
        int right = max;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (sumTime(piles, mid) < h) {
                right = mid - 1;
            } else if (sumTime(piles, mid) > h) {
                left = mid + 1;
            } else if (sumTime(piles, mid) == h) {
                right = mid - 1;
            }
        }
        return left;
    }

    private int sumTime(int[] piles, int k) {
        int sum = 0;
        for (int i = 0; i < piles.length; i++) {
            if (piles[i] % k != 0) {
                sum += piles[i] / k + 1;
            } else {
                sum += piles[i] / k;
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        int[] piles = new int[]{3, 6, 7, 11};
        int h = 8;
        MinEatingSpeed minEatingSpeed = new MinEatingSpeed();
        System.out.println(minEatingSpeed.minEatingSpeed(piles, h));
    }
}
